from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max,Q,F,Min,Avg,Count,Sum
from django.contrib.auth.hashers import make_password,check_password
import datetime # 导入时间包
import time
import random
from utils.comm import send_message
from utils.comm import get_redis_conn
from .ser import *
from django.http import HttpResponse
from meiduo01.models import *

# Create your views here.

# 读取首页三级分类
class Home(APIView):
    def get(self,request):
        # 读取一级             filter过滤的意思 parent_id_isnull=True是为空的意思 为空的化就是一级
        cates=Category.objects.filter(parent_id__isnull=True).all()
        print(cates)
        # 定义一个空列表
        list=[]
        # 循环
        for i in cates:
            # 定义一个空字典
            dict={}
            # 以键值对的形式添加信息
            dict['id']=i.id
            dict['name']=i.name
            # 读取二级 反向查询获取一级下的二级  subs是模型层中定义的反查询
            two=i.subs.all()
            print(two)
            twolist=[]
            # 遍历二级获取三级
            for j in two:
                # 定义空字典
                twodict={}
                # 以键值对的形式添加
                twodict['id']=j.id
                twodict['name']=j.name
                # 反查询
                three=j.subs.all()
                # 调用序列化器
                ser=CateSer(three,many=True)
                # 字典的添加
                twodict['subs']=ser.data
                # 把字典添加到列表twolist中
                twolist.append(twodict)

            dict['subs']=twolist
            list.append(dict)
        # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods=[]
        for j in cates:
            dict={}
            dict['id']=j.id
            dict['name']=j.name
            dict['pic']=str(j.pic)
            two=j.subs.all()
            twoser=CateSer(two,many=True)
            dict['two']=twoser.data
            # 获取三级
            three=Category.objects.filter(top_parent=j.id,level=3).all()
            threeser=CateSer(three,many=True)
            dict['three']=threeser.data
            # 获取商品，排序，新品按时间倒序排，价格，销量
            sorted=request.GET.get('sorted')
            topid=request.GET.get('topid')
            goods=Goods.objects.filter(category1_id=j.id,home_show=1).all()
            if sorted:
                if int(topid)==int(j.id):
                    goods=Goods.objects.filter(category1_id=j.id,home_show=1).order_by('-'+sorted).all()
            gser=GoodsSer(goods,many=True)
            dict['goods']=gser.data
            categoods.append(dict)


        return Response({'code':200,'catelist':list,'categoods':categoods})


